<template>
  <div class="box" style="">
    <el-row style="display: flex;flex-wrap: wrap">
      <el-col :span="24" style="display: flex">
        <div style="width: 30%;text-align: right">
          对象通知模版：
        </div>
        <el-input v-model="form.template" size="small" style="width: 50%" :disabled="true"/>
        <el-button size="small" icon="el-icon-plus" @click="selectEvent" type="primary" style="margin-left: 5px">选择
        </el-button>
      </el-col>
      <el-col :span="24" style="display: flex;margin-top: 5px">
        <div style="width: 30%;text-align: right">
          选择组：
        </div>
        <el-select v-model="form.group" placeholder="请选择" style="width: 50%" clearable size="small">
          <el-option v-for="dict in groupOptions" :key="dict.dictValue" :label="dict.dictLabel"
                     :value="dict.dictValue"/>
        </el-select>
        <el-button size="small" icon="el-icon-plus" @click="groupAdd" type="primary" style="margin-left: 5px">增加
        </el-button>
      </el-col>
      <el-col :span="24" style="display: flex;margin-top: 5px">
        <div style="width: 30%;text-align: right">
          号码：
        </div>
        <el-input v-model="form.number" size="small" style="width: 50%"/>
        <add-button @click="numberAdd" text="增加" style="margin-left: 5px"/>
      </el-col>
      <el-col :span="24" style="display: flex;margin-top: 5px">
        <div style="width: 30%;text-align: right">
          组织人员：
        </div>
        <el-select
          v-model="form.user"
          size="small"
          filterable
          style="width: 50%"
          remote
          :loading="loading"
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod">
          <el-option
            v-for="item in options"
            :key="item.userId"
            :label="item.label"
            :value="item.userId">
          </el-option>
        </el-select>
        <!--        <el-input v-model="form.user" size="small" style="width: 50%"/>-->
        <add-button @click="userAdd" text="增加" style="margin-left: 5px"/>
      </el-col>
      <el-col :span="22" :offset="1" style="margin-top: 5px">
        <el-button type="primary" size="small" @click="selectUser">选择组织人员</el-button>
        <el-button type="primary" style="margin-left: 5px" size="small" @click="selectObject">选择消息对象</el-button>
      </el-col>
      <el-col :span="24">
        <el-table
          class="config-table "
          :data="tableData"
          border
          stripe
          fit
          highlight-current-row
          :header-cell-style="{background:'#f6f7fa','margin-top':'5px','width':'50%'}"
          style="width: 98%;margin: 10px 1%">
          <el-table-column label="类型" align="center" prop="NOTICE_OBJECT_TYPE" width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.NOTICE_OBJECT_TYPE_LABEL">{{ scope.row.NOTICE_OBJECT_TYPE_LABEL }}</span>
              <span v-else>{{ scope.row.NOTICE_OBJECT_TYPE }}</span>
            </template>

          </el-table-column>
          <el-table-column label="对象" align="center" prop="NOTICE_OBJECT_TEMPLATE_ID" width="150"
                           show-overflow-tooltip>
            <template slot-scope="scope">
            <span v-if="scope.row.NOTICE_OBJECT_TEMPLATE_ID_LABEL">{{
                scope.row.NOTICE_OBJECT_TEMPLATE_ID_LABEL
              }}</span>
              <span v-else>{{ scope.row.NOTICE_OBJECT_TEMPLATE_ID }}</span>
            </template>
          </el-table-column>
          <el-table-column label="消息模版" align="center" prop="NOTICE_TEMPLATE_ID" show-overflow-tooltip>
            <template slot-scope="scope">
            <span v-if="scope.row.NOTICE_TEMPLATE_ID_LABEL">{{
                scope.row.NOTICE_TEMPLATE_ID_LABEL
              }}</span>
              <span v-else>{{ scope.row.NOTICE_TEMPLATE_ID }}</span>
            </template>
          </el-table-column>
          <el-table-column label="通知次数" align="center" prop="NOTICE_NUM" width="150">
            <template slot="header" slot-scope="scope">
              <span><span style="color: red;font-size: 16px">* </span>通知次数</span>
            </template>
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.NOTICE_NUM" controls-position="right" :min="1" style="width: 100%"/>
            </template>
          </el-table-column>
          <el-table-column label="（间隔时间（分）)" align="center" prop="NOTICE_INTERVAL" width="150">
            <template slot="header" slot-scope="scope">
              <span><span style="color: red;font-size: 16px">*</span>（间隔时间（分）)</span>
            </template>
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.NOTICE_INTERVAL" controls-position="right" :min="1"
                               style="width: 90%"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template slot-scope="scope">
                <span @click="removeData(scope.$index)"
                      style="color: red;margin-left: 5px;cursor: pointer">
                  删除
                </span>

            </template>
          </el-table-column>
        </el-table>

      </el-col>
      <el-col>
        <list-dialog :listForm="listForm" v-if="listForm.open" :item="item" @selectedRow='selectedRow' ref="listRef"/>
        <tree-dialog :treeForm="treeForm" v-if="treeForm.open" :item="item" @selectedTreeRow='selectedTreeRow'
                     ref="treeRef"/>

      </el-col>

    </el-row>
  </div>
</template>

<script>

import listDialog from "@/components/CustomizeForm/listDialog.vue";
import treeDialog from "@/components/CustomizeForm/treeDialog.vue";
import {postAction} from "@/platform/uni/api/uni/element/index.ts";

export default {
  name: "messageInfo",
  components: {treeDialog, listDialog},
  props: {
    actionList: {
      type: Array,
      default: () => []
    },
    item: {
      type: Object,
      default: {}
    }
  },
  computed: {
    data: {
      get() {
        const item = this.item || {}
        return item.value || []
      }
    },
  },
  watch: {
    data: {
      handler(value) {
        if (value) {
          if (value && typeof value == 'string' && value != '[]') {
            let data = JSON.parse(value);
            data.map(e => {
              if (e.NOTICE_TEMPLATE_ID && !e.NOTICE_TEMPLATE_ID_LABEL) {
                e.NOTICE_TEMPLATE_ID_LABEL = e.NOTICE_TEMPLATE_ID;
              }
            });
            this.tableData = data;
          }
        }
      },
      deep: true,
      immediate: true
    },
    tableData: {
      handler(value) {
        if (value) {
          this.$set(this.item, 'value', JSON.stringify(value));
          this.$set(this.item, 'label', value.map(e => e.NOTICE_OBJECT_TYPE).join(','));
        }
      },
      deep: true,
      immediate: true
    },
  },
  data() {
    return {
      tableData: [],
      loading: false,
      options: [],
      treeForm: {
        defaultExpandAll: false,//是否多选
        multiple: false, //this.config.multiple || false,//是否多选
        extraForm: {},
        open: false,
        // 标题
        title: '',
        // 请求路径
        path: '',
        isLazy: true//this.config.isLazy || false,//是否懒加载
      },
      listForm: {
        multiple: false,
        extraForm: {},
        searchColumn: '',
        prop: '',
        showField: '',
        valueField: '',
        searchType: '',
        open: false,
        // 标题
        title: '',
        // 请求路径
        path: '',
        // 请求参数
        queryParams: {},
        // 显示列字段
        columns: [],
      },
      // tableData: [],
      form: {},
      groupOptions: [],
    }
  },
  created() {
    postAction('/rule/view/type/commonIntf', {elementCode: 'MSG_NOTICE_OBJECT_TYPE',}).then(
      response => {
        this.groupOptions = response.data;
      }
    );
  },
  methods: {
    // initTable(val) {
    //   if (val && typeof val == 'string')
    //     this.tableData = JSON.parse(val);
    // },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = false;
        this.options = []
        postAction('/rule/view/type/commonIntf', {
          elementCode: 'ORG_USER_LIST'
        }).then(
          response => {
            if (response.data) {
              response.data.map((e) => {
                e.label = `${e.realName}(${e.userName}/${e.phoneNum}-${e.orgPathName})`
              })
              this.options = response.data;
            }
            this.loading = false;
          }
        );
      } else {
        this.options = [];
      }
    },
    // 设置搜索头
    setSearchColumn() {
      let arr = [];
      if (this.listForm.showField) {
        arr.push(
          {
            prop: this.listForm.showField,
            label: this.listForm.showField
          }
        )
      }
      if (this.listForm.valueField) {
        arr.push(
          {
            prop: this.listForm.valueField,
            label: this.listForm.valueField
          }
        )
      }
      return arr

    },
    selectedTreeRow(val) {
      let data = val.map(e => e[this.treeForm.valueField]);
      let dataShow = val.map(e => e[this.treeForm.showField]);
      this.$set(this.form, this.treeForm.prop + 'Value', data.join(','));
      this.$set(this.form, this.listForm.prop, dataShow.join(','));
      let detail = {
        NOTICE_OBJECT_TYPE: val.map(e => e['type']).join(','),
        NOTICE_OBJECT_TYPE_LABEL: val.map(e => e['type']).join(','),
        NOTICE_OBJECT_TEMPLATE_ID: this.form[this.treeForm.prop + 'Value'],
        NOTICE_OBJECT_TEMPLATE_ID_LABEL: this.form[this.treeForm.prop],
        NOTICE_TEMPLATE_ID: this.form['templateValue'],
        NOTICE_TEMPLATE_ID_LABEL: this.form['template'],
        NOTICE_NUM: '',
        NOTICE_INTERVAL: '',
      };
      this.addData(detail);
    },
    // 列表选中的行
    selectedRow(val) {

      console.log(val)
      if (this.listForm.multiple) {
        let data = val.map(e => e[this.listForm.valueField]);
        let dataShow = val.map(e => e[this.listForm.showField]);
        this.$set(this.form, this.listForm.prop + 'Value', data.join(','));
        this.$set(this.form, this.listForm.prop, dataShow.join(','));
      } else {
        // 回显的字段内容
        this.value = val[this.listForm.valueField];
        this.$set(this.form, this.listForm.prop + 'Value', val[this.listForm.valueField]);
        this.$set(this.form, this.listForm.prop, val[this.listForm.showField]);
      }
      if (this.listForm.prop != 'template') {
        let data = {
          NOTICE_OBJECT_TYPE: this.form[this.listForm.prop + 'Value'],
          NOTICE_OBJECT_TYPE_LABEL: this.form[this.listForm.prop],
          NOTICE_OBJECT_TEMPLATE_ID: this.form[this.listForm.prop + 'Value'],
          NOTICE_OBJECT_TEMPLATE_ID_LABEL: this.form[this.listForm.prop],
          NOTICE_TEMPLATE_ID: this.form['templateValue'],
          NOTICE_TEMPLATE_ID_LABEL: this.form['template'],
          NOTICE_NUM: '',
          NOTICE_INTERVAL: '',
        };
        this.addData(data);
      }
    },
    groupAdd() {
      let data = {
        NOTICE_OBJECT_TYPE: this.form.group,
        NOTICE_OBJECT_TEMPLATE_ID: this.form.group,
        NOTICE_TEMPLATE_ID: this.form['templateValue'],
        NOTICE_TEMPLATE_ID_LABEL: this.form['template'],
        NOTICE_NUM: '',
        NOTICE_INTERVAL: '',
      };
      this.addData(data);
    },
    numberAdd() {
      let data = {
        NOTICE_OBJECT_TYPE: this.form.number,
        NOTICE_OBJECT_TEMPLATE_ID: this.form.number,
        NOTICE_TEMPLATE_ID: this.form['templateValue'],
        NOTICE_TEMPLATE_ID_LABEL: this.form['template'],
        NOTICE_NUM: '',
        NOTICE_INTERVAL: '',
      };
      this.addData(data);
    },
    userAdd() {
      let data = {
        NOTICE_OBJECT_TYPE: "E",
        NOTICE_OBJECT_TEMPLATE_ID: this.form.user,
        NOTICE_TEMPLATE_ID: this.form['templateValue'],
        NOTICE_TEMPLATE_ID_LABEL: this.form['template'],
        NOTICE_NUM: '',
        NOTICE_INTERVAL: '',
      };
      this.addData(data);
    },
    selectEvent() {
      this.$set(this.listForm, 'title', '对象通知模版选择');
      this.$set(this.listForm, 'path', '/rule/view/type/commonIntf');
      this.$set(this.listForm, 'extraForm', {
        elementCode: 'MSG_TACTIC_NOTICE_TEMPLATE_ID',
      });
      this.$set(this.listForm, 'prop', 'template');
      this.$set(this.listForm, 'showField', 'templateName');
      this.$set(this.listForm, 'valueField', 'templateId');
      this.$set(this.listForm, 'searchColumn', this.setSearchColumn());
      this.$set(this.listForm, 'open', true);
      this.$nextTick(() => {
        this.$refs.listRef.getList();
      });


    },
    selectUser() {
      this.$set(this.treeForm, 'title', '组织人员选择');
      this.$set(this.treeForm, 'path', '/rule/view/type/commonIntf');
      this.$set(this.treeForm, 'extraForm', {
        elementCode: 'DISPATCH_TACTIC_DISPATCH_OBJECT',
      });
      this.$set(this.treeForm, 'prop', 'user');
      this.$set(this.treeForm, 'showField', 'name');
      this.$set(this.treeForm, 'valueField', 'id');
      this.$set(this.treeForm, 'open', true);
      this.$nextTick(() => {
        this.$refs.treeRef.getList();
      });
    },
    selectObject() {

      this.$set(this.listForm, 'title', '消息对象选择');
      this.$set(this.listForm, 'path', '/rule/view/type/commonIntf');
      this.$set(this.listForm, 'extraForm', {
        elementCode: 'MSG_OBJECT_LIST',
      });
      this.$set(this.listForm, 'prop', 'message');
      this.$set(this.listForm, 'showField', 'templateName');
      this.$set(this.listForm, 'valueField', 'templateId');
      this.$set(this.listForm, 'searchColumn', this.setSearchColumn());
      this.$set(this.listForm, 'open', true);
      this.$nextTick(() => {
        this.$refs.listRef.getList();
      });

    },
    addData(data) {
      if (!(data.NOTICE_OBJECT_TYPE && data.NOTICE_OBJECT_TEMPLATE_ID)) {
        this.$message.error('类型或者对象不能为空！')
        return
      }
      let time = this.actionList.find(e => e.paramObjectAttr === "NOTICE_INTERVAL" && e.paramObjectName === "MsgData");
      let num = this.actionList.find(e => e.paramObjectAttr === "NOTICE_NUM" && e.paramObjectName === "MsgData");
      data['NOTICE_INTERVAL'] = (time && Object.keys(time).length > 0) ? time.value * 1 : '';
      data['NOTICE_NUM'] = (num && Object.keys(num).length > 0) ? num.value * 1 : '';
      this.tableData.push(data);
    },
    removeData(index) {
      this.tableData.splice(index, 1);
    }
  }
}
</script>

<style>
.box {
  position: relative;
  width: 100%;
  /*height: 150px;*/
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 10px;
}

.box::after {
  content: '消息对象管理';
  position: absolute;
  left: 10px;
  top: -18px;
  width: 80px;
  text-align: center;
  font-size: 12px;
  color: black;
  font-weight: 900;
  background: #fff;
}

</style>
